#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
#include "GameAlgorithm.h"

using namespace cocos2d;
using namespace CocosDenshion;

#include <vector>
CCScene* HelloWorld::scene()
{
    // 'scene' is an autorelease object
    CCScene *scene = CCScene::create();
    
    // 'layer' is an autorelease object
    HelloWorld *layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !CCLayer::init() )
    {
        return false;
    }
    
    xspeed = 18;
    
    
    batchnode = CCSpriteBatchNode::create( "Icon.png" );
    this->addChild( batchnode );
    
    // add 10 random sprites
    CCSize size = CCDirector::sharedDirector()->getWinSize();
    int max = 100;
    
    
    for ( int i = 1; i <= max; i++ ) {
        CCSprite* sp = CCSprite::create( "Icon.png" );
        
        sp->setPosition( ccp( CCRANDOM_0_1() * size.width*2 + sp->getContentSize().width / 2, CCRANDOM_0_1() * size.height));
//        this->addChild( sp );
        batchnode->addChild( sp );
        list.push_back( sp );
    }
    
    test = CCSprite::create( "Icon-72.png" );
    this->addChild( test ,11);
    test->setColor( ccRED );
    test->setPosition( ccp( CCRANDOM_0_1() * size.width + test->getContentSize().width / 2, CCRANDOM_0_1() * size.height));

    this->schedule( schedule_selector(HelloWorld::move), 0.016f);
    
 
    return true;
}

void HelloWorld::move(float dt ){
    
    std::vector<CCSprite*>::iterator it = list.begin();
    
    while ( it != list.end()) {
        (*it)->setColor(ccWHITE);
        
        it++;
    }
    
    
    
    CCSize size = CCDirector::sharedDirector()->getWinSize();
    test->setPositionX( test->getPositionX() + xspeed );
    
    if ( test->getPositionX() <= test->getContentSize().width / 2) {
        xspeed = 18;
    }else if( test->getPositionX() >size.width ){
        
        xspeed = -18;
    }
  
    
    coll_logic();
    
}


void HelloWorld::coll_logic(){
    
    CCSize size = CCDirector::sharedDirector()->getWinSize();
    
    QuadTree tree( 0,CCRectMake(0,size.height , size.width , size.height) );
    
    
    std::vector<CCSprite*>::iterator it = list.begin();
    
    while ( it!= list.end() ) {
        
        tree.insert( *it );
        
        it++;
    }
  
    
    CCArray* result = tree.retrive( test );
    
    CCObject* obj = NULL;
    
    CCARRAY_FOREACH(result, obj){
        CCSprite* sp = (CCSprite*)obj;
        sp->setColor(ccGREEN);
        
    }
    
    tree.clear(); // 清除对象
    
    CCLOG( "碰撞的个数:%i",result->count());
    
}

void HelloWorld::menuCloseCallback(CCObject* pSender)
{
    CCDirector::sharedDirector()->end();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
}
